import socket

import arrow

from msg.protocol import Protocol
from common.conf import conf
from common.tools import Tool
from msg.invite_or_not import CanInvite


class Order:
    def __init__(self):
        self.c = conf
        self.t = Tool()
        self.p = Protocol()

    # 同一个端口同一路摄像头,推了下一个,上一个就没了
    #
    def extract(self, s):
        cid_chan = s.split("@")[-1]
        l = cid_chan.split("&")
        return l[0], l[1]

    def invite_local(self, cam_id, chan_id):
        q = {"cam_id": cam_id, "ty": "msg"}

        msg = self.c.col.find_one(q)
        if msg is None: return
        # 获取报文
        cid, inv_msg = self.p.invite(msg['msg'], cam_id, chan_id, msg['ip'], msg['port'])
        # print(inv_msg)
        ssrc = self.t.from_camId_chanId_to_ssrc(cam_id, chan_id)
        if not CanInvite().can_invite(cam_id, chan_id):
            print("不可以invite!!!!!!!!!!!!!!!!!", ssrc)
            return
        print("发出invite", ssrc, msg['ip'], msg['port'])
        print(inv_msg)
        self.c.conn.sendto(inv_msg.encode(), (msg['ip'], msg['port']))
        q = {"ty": "invite", "cam_id": cam_id, "chan_id": chan_id}
        # call id 提供invite ok可以对上  是nvr 6+chan 2
        d = {"call_id": cid, "invite": inv_msg, "time": arrow.now().format()[:19]}
        self.c.col.update_one(q, {"$set": d}, upsert=True)

    def invite_remote(self, cid, chan):
        s = f"CSeq: 99 WQ ORDER@{cid}&{chan}"
        print(s)
        ssrc = Tool().from_camId_chanId_to_ssrc(cid, chan)
        print(ssrc)
        sock = socket.socket(socket.AF_INET,
                             socket.SOCK_DGRAM)
        sock.sendto(s.encode(), ("39.106.152.15", 5061))

    def bye_remote(self, cid, chan):
        s = f"CSeq: 98 WQ STOP@{cid}&{chan}"
        sock = socket.socket(socket.AF_INET,
                             socket.SOCK_DGRAM)
        sock.sendto(s.encode(), ("39.106.152.15", 5061))

    def bye_local(self, cid, chan):

        q = {"cam_id": cid, "ty": "msg"}

        msg = self.c.col.find_one(q)
        if msg is None: return

        d = self.query_invite(cid, chan)
        if d is None:
            print("找不到曾经的invite")
            return
        ivs = d['invite']
        to_tag = d.get("to_tag", "")
        if to_tag == "":
            print("找不到曾经的to tag,本应该invite ok给 ")
            return
        by = Protocol().bye_invite(ivs, to_tag)
        print("发送bye")
        self.c.conn.sendto(by.encode(), (msg['ip'], msg['port']))

    def query_invite(self, cid, chan):
        q = {"ty": "invite", "cam_id": cid, "chan_id": chan}
        return self.c.col.find_one(q)


if __name__ == '__main__':
    # http://39.106.152.15/deploy/static/h264/000CA/live/index.m3u8
    a = Order()
    cid = "34020000001110009999"
    chan1 = "34020000001320000001"
    a.bye_local(cid, chan1)
    # a.invite_local(cid, chan1)
